﻿/* $Author: alexander.bsrgin@gmail.com $
 * $Id: MainActivity.java 10 2011-11-14 17:39:43Z alexander.bsrgin@gmail.com $
 * 
 */
package ru.habrahabr.prettyalarm;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

// см. http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
// см. http://stackoverflow.com/questions/680180/where-to-stop-destroy-threads-in-android-service-class
public class MainActivity extends Activity
{
	private static volatile Handler handler;
	private static volatile Thread thread;
	private static volatile TextView textViewCurrentTime = null;
	private static volatile TextView textViewLeftTime = null;
	private static String[] hour_strings = null;
	
	static Date alarm = null; // TODO удалить и перенести это в настройки
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		
		alarm = new Date(new Date().getTime() + 8*60*60000 + 2*60000); // TODO удалить это отсюда
		
		// кэшируем склонения час, часов, часа
		if (hour_strings == null)
		{
			hour_strings = new String[3];
			hour_strings[0] = getString(R.string.left_time_1hour);
			hour_strings[1] = getString(R.string.left_time_234hours);
			hour_strings[2] = getString(R.string.left_time_567890TENhours);
		}
		
		// создаём handler для обновления UI
		handler = new Handler();
		// проверяем, и.б. поток уже запущен?
		thread = (Thread) getLastNonConfigurationInstance();
		if (thread != null && thread.isAlive()) {
			//dialog = ProgressDialog.show(this, "Download", "downloading");
		}
		
		// Portrait
		Button btnOff = (Button) findViewById(R.id.main_btn_off);
		if (btnOff != null)
			btnOff.setOnClickListener(new ClickListener());
		Button btnSave = (Button) findViewById(R.id.main_btn_save);
		if (btnSave != null)
			btnSave.setOnClickListener(new ClickListener());
		Button btnLight = (Button) findViewById(R.id.main_btn_light);
		if (btnLight != null)
			btnLight.setOnClickListener(new ClickListener());

		// Landscape
		if (findViewById(R.id.main_current_time) != null)
		{
			startThread();
		}
		else
		{
			stopThread();
		}
		
		startThread();
	}
	
	@Override
	protected void onPause()
	{
		stopThread();
		super.onPause();
	}

	// сохранение потока
	@Override
	public Object onRetainNonConfigurationInstance()
	{
		return thread;
	}
	
	private synchronized void startThread()
	{
		if (thread == null)
		{
			textViewCurrentTime = (TextView) findViewById(R.id.main_current_time);
			textViewLeftTime = (TextView) findViewById(R.id.main_left_time);
			updateCurrentTime();
			handler = new Handler();
			thread = new UpdateUIThread();
			thread.start();
		}
	}
	
	private synchronized void stopThread()
	{
		if (thread != null)
		{
			Thread moribund = thread;
			thread = null;
			moribund.interrupt();
			handler = null;
			textViewCurrentTime = null;
			textViewLeftTime = null;
		}
	}
	
	private static void updateCurrentTime()
	{
		if (textViewCurrentTime == null || textViewLeftTime == null) return;
		final Date now = new Date();
		textViewCurrentTime.setText(new SimpleDateFormat("HH:mm:ss").format(now));
		
		if (alarm.before(now))
		{
			textViewLeftTime.setText("");
			return;
		}

		long diff_ms = alarm.getTime() - now.getTime();
		Date diff =  new Date(diff_ms);
		final int d = diff.getDate();
		if (d > 1)
		{
			textViewLeftTime.setText("");
			return;
		}
		
		final int h = diff.getHours();
		final int m = diff.getMinutes();
		String h_str;
		if (h >= 5 && h <= 19)
			h_str = hour_strings[2];
		else
		{
			switch (h%10)
			{
			case 1: h_str = hour_strings[0]; break;
			case 2: case 3: case 4: h_str = hour_strings[1]; break;
			default: h_str = hour_strings[2]; break;
			}
		}
		Context c = AlarmApplication.getInstance().getApplicationContext();
		String left_details;
		if (h == 0)
			left_details = String.format(c.getString(R.string.left_time_m_min), m);
		else if (m == 0)
			left_details = String.format(c.getString(R.string.left_time_n_hours), h, h_str);
		else
			left_details = String.format(c.getString(R.string.left_time_n_hours_m_min), h, h_str, m);
		
		textViewLeftTime.setText(left_details);
	}
	
	private class ClickListener implements OnClickListener
	{
		public void onClick(View v)
		{
			AlarmApplication.vibrate();
			switch (v.getId())
			{
			case R.id.main_btn_off:
				Toast.makeText(MainActivity.this, "Off", Toast.LENGTH_SHORT).show();
				break;
			case R.id.main_btn_save:
				Toast.makeText(MainActivity.this, "Save", Toast.LENGTH_SHORT).show();
				break;
			case R.id.main_btn_light:
				Toast.makeText(MainActivity.this, "Light", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	}
	
	static public class UpdateUIThread extends Thread
	{
		@Override
		public void run() {
			while(Thread.currentThread() == thread) {
				try {
					Thread.sleep(1000);
					if (handler != null) {
						handler.post(new Runnable() {
							public void run() {
								updateCurrentTime();
							}
						});
					}
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				} catch(Exception e) {
					Thread.currentThread().interrupt();
				}
			}
		}
	}
}